/**
 * Created by XianTao on 2016/11/9
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.jpa.base.util;

import org.springframework.data.domain.Sort;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

public class ServletUtil {
    /**
     * 取得带前缀为search_的Request Parameters
     * <p/>
     * 返回的结果的Parameter名已去除前缀.
     */
    public static Map<String, Object> getParametersStartingWithSearch(ServletRequest request) {
        return getParametersStartingWith(request, "search_");
    }

    /**
     * 取得带前缀为sort_的Request Parameters，且key为待排序字段，value为排序顺序（固定为asc或desc）
     * <p/>
     * 返回的结果为排序方式
     */
    public static Sort getParametersStartingWithSort(ServletRequest request) {
        Map<String, Object> sortParams = getParametersStartingWith(request, "sort_");
        if (!ObjectUtils.isEmpty(sortParams)) {
            List<Sort.Order> orders = new ArrayList<Sort.Order>();
            for (Map.Entry<String, Object> entry : sortParams.entrySet()) {
                //过滤空值
                String key = entry.getKey();
                Object value = entry.getValue();
                if (StringUtils.isEmpty(value)) {
                    continue;
                }
                orders.add(new Sort.Order(Sort.Direction.fromString(String.valueOf(value)), key));
            }
            return new Sort(orders);
        }
        return null;
    }

    /**
     * 取得带相同前缀的Request Parameters
     * <p/>
     * 返回的结果的Parameter名已去除前缀.
     */
    public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap<String, Object>();
        if (prefix == null) {
            prefix = "";
        }
        while ((paramNames != null) && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if ("".equals(prefix) || paramName.startsWith(prefix)) {
                String unPrefixed = paramName.substring(prefix.length());
                String[] values = request.getParameterValues(paramName);
                if ((values == null) || (values.length == 0)) {
                    // Do nothing, no values found at all.
                } else if (values.length > 1) {
                    params.put(unPrefixed, values);
                } else {
                    try {
                        params.put(unPrefixed, URLDecoder.decode(values[0], "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        params.put(unPrefixed, values[0]);
                    }
                }
            }
        }
        return params;
    }
}
